//
//  NWPictureCollectionVC.swift
//  9-picturePicker
//
//  Created by 牛威 on 15/12/16.
//  Copyright © 2015年 牛威. All rights reserved.
//

import UIKit

private let margin = UIScreen.mainScreen().scale * 4

private let NWPictureCollectionCellID = "NWPictureCollectionCellID"

class NWPictureCollectionVC: UICollectionViewController {
    
    
    //MARK: - 懒加载一个照片数组
    
     lazy var pictures = [UIImage]()
    
    //当前用户选中的索引
    
    private  var selected = 0
    
    
    init(){
    
      super.init(collectionViewLayout: NWPictureCollectionFlowlayout())

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    

    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        
        //切记这里的colletionView跟view不是一回事 但是tableViewVC中是一回事
        
        collectionView?.backgroundColor = UIColor(white: 0.9, alpha: 1)
        
        //注册cell

        self.collectionView!.registerClass(NWPictureCollectionCell.self, forCellWithReuseIdentifier: NWPictureCollectionCellID)

    }
    
    
    //MARK: - 照片选择器布局
    
    private class NWPictureCollectionFlowlayout : UICollectionViewFlowLayout {
    
        
        private override func prepareLayout() {
            super.prepareLayout()
            
            let count :CGFloat =  4
            
            let w = (UIScreen.mainScreen().bounds.width - (count+1) * margin)/4
            
            itemSize = CGSize(width: w, height: w)
            
            minimumInteritemSpacing = margin
            
            minimumLineSpacing = margin
            
          sectionInset =  UIEdgeInsetsMake(margin, margin, 0, margin)
            
            
        }
    
        
    }

}

//MARK: - 数据源方法

extension NWPictureCollectionVC{
    
    

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        //这样就能保证始终在最后有一个+号按钮
        
        return pictures.count + 1
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(NWPictureCollectionCellID, forIndexPath: indexPath) as! NWPictureCollectionCell
        
        
        cell.image = (indexPath.item < pictures.count) ? pictures[indexPath.item] : nil
        
        cell.pictureDelegate = self
        
        return cell
    }

}


//MARK: - 实现代理方法

extension NWPictureCollectionVC : PictureDelegate {

    
    //添加照片
   
    @objc private func pictureDelegateDidAdd(cell: NWPictureCollectionCell) {
        
        //PhotoLibrary      保存的照片(可以删除)+同步的照片(不可以删除)
        //SavedPhotosAlbum 保存的照片-->屏幕截图+拍照
        //判断用户有没有权限访问相册
        
        if !UIImagePickerController.isSourceTypeAvailable(.SavedPhotosAlbum) {
        
        
           print("无法访问您的照片")
            
            return
        
        }
        
        //记录当前用户选中的索引
        
        selected = (collectionView?.indexPathForCell(cell)?.item) ?? 0
        
        
        //实例化一个选择器
        
        let picker = UIImagePickerController()
        
        //切记这里的picker遵守了两个协议,所以会自动的dismiss
        
        presentViewController(picker, animated: true, completion: nil)
        
        //要想选择照片必须实现代理方法
        
        
        picker.delegate = self
        
        
        
    }
    
    //删除照片
    
    @objc private func pictureDelegateDidRemove(cell: NWPictureCollectionCell) {
        
        //获取照片索引
        
        let indexPath = collectionView!.indexPathForCell(cell)!
        
        //判断是否达到上限
        
        if indexPath.item >= pictures.count {
        
        
           return
        
        }
        
        //删除选中数据
        
        pictures.removeAtIndex(indexPath.item)
        
        
        //动画刷新视图 - 重新调用数据行数的数据源方法
        //(内部实现要求 3 － 删除一个 indexPath － 数据源方法如果不返回 2，就会崩溃！)
        // collectionView?.deleteItemsAtIndexPaths([indexPath])
        // reloadData 方法只是单纯的刷新数据，没有动画，但是不会检测具体的 item 的数量

        
        collectionView?.reloadData()
    }
  

}

//MARK: - UIImagePickerControllerDelegate, UINavigationControllerDelegate

extension NWPictureCollectionVC :UIImagePickerControllerDelegate, UINavigationControllerDelegate {
  
    
    
    
    //注意:一旦实现这个代理方法就需要手动dismiss控制器
    ///
    /// - parameter picker: 照片选择控制器
    /// - parameter info:   照片信息字典
    
    
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        
//        print(info)
        
        let image = info["UIImagePickerControllerOriginalImage"] as! UIImage
        
        let scaleImage = image.scaleToWidth(600)
        
        if selected >= pictures.count {
        
            pictures.append(scaleImage)

        
        }else {
        
          pictures[selected] = scaleImage
        
        }
        
        
        collectionView?.reloadData()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
   

}

//MARK: - 使用代理监听按钮的点击
//如果协议中包含 optional 需要添加@objc修饰

@objc

private protocol PictureDelegate : NSObjectProtocol {

  
  optional  func pictureDelegateDidAdd(cell : NWPictureCollectionCell)
    
    optional  func pictureDelegateDidRemove(cell : NWPictureCollectionCell)

  


}

//MARK: - 自定义cell 如果是拿private修饰类 内部的一切方法和属性都是私有的 
//运行循环在找方法的时候就会找不到 就会经典提示错误 所以要在方法前加上@objec

private class NWPictureCollectionCell : UICollectionViewCell {
    
    
    //定义代理属性
    
    private var pictureDelegate : PictureDelegate?
    
    //设置image属性
    
    private var image : UIImage? {
    
    
        didSet {
        
         addBtn.setImage(image ?? UIImage(named: "compose_pic_add") , forState: .Normal)
            
            //如果数组没有照片就隐藏
            
         removeBtn.hidden = image == nil
        
        }
    
     }
    
    //MARK: - 按钮的监听方法
    
   @objc func removeMethod(){
    
    
        pictureDelegate!.pictureDelegateDidRemove?(self)
    
    }
    
   @objc func addMethod(){
    
       pictureDelegate!.pictureDelegateDidAdd?(self)
    
    }
    
    //MARK: - 构造函数

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    func setupUI(){
    
    
       //添加控件
        
        contentView.addSubview(addBtn)
        contentView.addSubview(removeBtn)
        
        //设置布局
        
        addBtn.frame = bounds
        
        removeBtn.snp_makeConstraints { (make) -> Void in
            
            make.right.equalTo(contentView.snp_right)
            make.top.equalTo(contentView.snp_top)
        }
        
        //添加监听方法
        
        removeBtn.addTarget(self, action: "removeMethod", forControlEvents: .TouchUpInside)
        addBtn.addTarget(self, action: "addMethod", forControlEvents: .TouchUpInside)
        
        //设置addbtn的填充模式
        
        addBtn.imageView?.contentMode = .ScaleAspectFill
    
    }

    
    //MARK: - 懒加载控件
    
    private lazy var removeBtn = UIButton(imgName: "compose_photo_close", backImage: "")
    
    private lazy var addBtn  = UIButton (imgName: "compose_pic_add", backImage: "")
}











